﻿using System;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace P7DC.Common.Attribute
{
	public class LocalizationAttribute : ActionFilterAttribute
	{
		private const string LangCookiesKey = "lang";

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			HttpContextBase ctx = filterContext.HttpContext;
			HttpCookie langCookie = ctx.Request.Cookies[LangCookiesKey];
			string[] userLanguages = ctx.Request.UserLanguages;

			var language = "en";

			if (langCookie != null)
			{
				language = langCookie.Value;
			}
			else if (userLanguages!=null && userLanguages.Length > 0)
			{
				language = userLanguages[0];
				ctx.Response.AppendCookie(CreateCookie(language));
			}

			Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);

			base.OnActionExecuting(filterContext);
		}

		protected static HttpCookie CreateCookie(string language)
		{
			return new HttpCookie(LangCookiesKey) { Value = language, Expires = DateTime.Now.AddYears(1) };
		}
	}
}
